package com.ujson.chat.client.command;

import com.ujson.base.common.task.AsyncTask;
import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.client.builder.ChatMessageBuilder;
import com.ujson.chat.client.dto.ChatInputDto;
import com.ujson.chat.client.session.ClientSession;
import com.ujson.chat.common.enums.ConsoleCommandType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Scanner;

/**
 * <h3>ujson-parent</h3>
 * <p>控制台聊天命令</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-22 21:25
 */
@Slf4j
@Service
public class ChatConsoleCommand extends ConsoleCommand<ChatInputDto> {
    @Autowired
    private ChatMessageBuilder chatMessageBuilder;

    private String inputString;
    private String messagePattern = "\\S+@\\S+";
    public ConsoleCommandType getType() {
        return ConsoleCommandType.CHAT;
    }

    public ChatInputDto getInput() {
        return ChatInputDto.create(inputString);
    }

    @Override
    public String getMatchPattern() {
        return this.messagePattern;
    }

    public void exec(Scanner scanner) {
        System.err.println("请输入聊天信息(uid@message):");
        while (!checkCommand(inputString = scanner.next())) {
            System.out.println("聊天信息格式不合法, 请重新输入(uid@message):");
        }

        LogUtil.info(log, "chat input: " + getInput());
        doChat();
    }

    public void doChat() {
        AsyncTask.addTask(() ->{
            ChatMessageBuilder.MessageExt messageExt = new ChatMessageBuilder.MessageExt();
            messageExt.setMsgType(ChatMessageBuilder.MsgType.TEXT);
            getClientSession().sendMsg(chatMessageBuilder.build(getChannel(), getInput(), messageExt));
        });
    }

}
